package com.map.lbs;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import com.baidu.mapapi.BMapManager;
import com.baidu.mapapi.GeoPoint;
import com.baidu.mapapi.ItemizedOverlay;
import com.baidu.mapapi.LocationListener;
import com.baidu.mapapi.MKMapViewListener;
import com.baidu.mapapi.MapActivity;
import com.baidu.mapapi.MapView;
import com.baidu.mapapi.MyLocationOverlay;
import com.baidu.mapapi.Projection;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.AlphaAnimation;
import android.widget.TextView;

public class MapStageActivity extends MapActivity {
	private MapView mapView;
	private View messageView;
	private GeoMessageOverlay messageOverlay;
	private int zoomLevel;
	private LocationListener locationListener; //onResume时注册此listener，onPause时需要Remove
	private MyLocationOverlay locationOverlay;
    private Message popup;
    private Location current;
    private MessageFactory messageFactory;
   
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        MapStageApp app = (MapStageApp)this.getApplication();
		if (app.mBMapMan == null) {
			app.mBMapMan = new BMapManager(getApplication());
			app.mBMapMan.init(app.mStrKey, new MapStageApp.MyGeneralListener());
		}
		app.mBMapMan.start();
        // 如果使用地图SDK，请初始化地图Activity
        super.initMapActivity(app.mBMapMan);
        
        mapView = (MapView) findViewById(R.id.bmapView);
        mapView.setBuiltInZoomControls(true);
        mapView.setDrawOverlayWhenZooming(true);
        
        Drawable marker = getResources().getDrawable(R.drawable.transport);  //得到需要标在地图上的资源
		marker.setBounds(0, 0, marker.getIntrinsicWidth(), marker
				.getIntrinsicHeight());   //为maker定义位置和边界
		
		messageFactory = new MockMessageFactory();
		
		messageOverlay = new GeoMessageOverlay(marker);
		mapView.getOverlays().add(messageOverlay);
		
		locationOverlay = new MyLocationOverlay(this, mapView);
		mapView.getOverlays().add(locationOverlay); 
        // 注册定位事件
        locationListener = new LocationListener(){

			@Override
			public void onLocationChanged(Location location) {
				if (location != null){
					if(current == null){
						GeoPoint pt = new GeoPoint((int)(location.getLatitude()*1e6),
								(int)(location.getLongitude()*1e6));
						mapView.getController().animateTo(pt);
					}
					current = location;
				}
			}
        };
		
        //Message view
		messageView = super.getLayoutInflater().inflate(R.layout.message_bubble, null);
		
		mapView.addView( messageView,
                new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
		messageView.setVisibility(View.GONE);
		messageView.setClickable(true);
		messageView.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				if(popup != null){
					Intent intent = new Intent();
					intent.setClass(MapStageActivity.this, MessageActivity.class);
					intent.putExtra("message_id", popup.getId());
					
					startActivity(intent);
					MapStageActivity.this.finish();
				}
			}
		});
		//Comments view
		zoomLevel = mapView.getZoomLevel();
		
		mapView.regMapViewListener(app.mBMapMan, new MKMapViewListener(){

			@Override
			public void onMapMoveFinish() {
				MapViewScope scope = new MapViewScope(mapView.getLatitudeSpan(), 
					mapView.getLongitudeSpan(), mapView.getMapCenter());
			
				Log.d(getPackageName(), scope.toString());
    	
	    	    List<Message> messages = messageFactory.fetchMessages(scope);
	    	    
	    	    synchronized(messageOverlay){
	    	    	messageOverlay.updateMessages(messages);
	    	    }
			}
			
		});
    }
    
    @Override
	protected void onPause() {
    	MapStageApp app = (MapStageApp)this.getApplication();
		app.mBMapMan.getLocationManager().removeUpdates(locationListener);
		locationOverlay.disableMyLocation();
       // locationOverlay.disableCompass(); // 关闭指南针
		app.mBMapMan.stop();
		super.onPause();
	}
	@Override
	protected void onResume() {
		MapStageApp app = (MapStageApp)this.getApplication();
		// 注册定位事件，定位后将地图移动到定位点
        app.mBMapMan.getLocationManager().requestLocationUpdates(locationListener);
        locationOverlay.enableMyLocation();
        //locationOverlay.enableCompass(); // 打开指南针
		app.mBMapMan.start();
		super.onResume();
	}

	@Override
	protected boolean isRouteDisplayed() {
		// TODO Auto-generated method stub
		return false;
	}
	
	class GeoMessageOverlay extends ItemizedOverlay<Message> {
		private Map<Long, Message> messageOverlayItems;
		private List<Long> messageIds;
		
		public GeoMessageOverlay(Drawable marker) {
			super(marker);
			messageOverlayItems = new ConcurrentHashMap<Long, Message>();
			messageIds = new ArrayList<Long>();
		}
		
		public void updateMessages(List<Message> messages){
			boolean changed = false;
			for(Message message : messages){
				if(!messageOverlayItems.containsKey(message.getId())){
				    messageIds.add(message.getId());
				    messageOverlayItems.put(message.getId(), message);
				    changed = true;
				}
			}
			
			if(changed){
				populate();
			}
		}

		@Override
		protected Message createItem(int index) {
			return messageOverlayItems.get(messageIds.get(index));
		}

		@Override
		public int size() {
			return messageOverlayItems.size();
		}
		
		@Override
		public void draw(Canvas canvas, MapView mapView, boolean shadow) {

			// Projection接口用于屏幕像素坐标和经纬度坐标之间的变换
			Projection projection = mapView.getProjection(); 
			for (int index = size() - 1; index >= 0; index--) { // 遍历mGeoList
				Message message = messageOverlayItems.get(messageIds.get(index)); // 得到给定索引的item
				Point point = projection.toPixels(message.getPoint(), null);
				//Drawable photo = new BitmapDrawable(getResources().openRawResource(R.drawable.face)).getCurrent();
				
				Bitmap photo = new BitmapDrawable(getResources().openRawResource(R.drawable.face)).getBitmap();
				//Bitmap background = bubble.getBitmap();
				Rect src = new Rect(0, 0, 140, 140);
				Rect dst = new Rect(point.x - 32, point.y - 32, point.x + 32, point.y + 32);
				canvas.drawBitmap(photo, src, dst, new Paint());
				//message.setMarker(photo);
				//canvas.drawBitmap(background, point.x-26, point.y-44, new Paint());
				//canvas.drawText(title, point.x-22, point.y-26, paintText); // 绘制文本
			}
			//super.draw(canvas, mapView, shadow);
		}
		
		@Override
		protected boolean onTap(int i) {
			setFocus(messageOverlay.getItem(i));
			// 更新气泡位置,并使之显示
			
			Message message = messageOverlayItems.get(messageIds.get(i));
			popup = message;
			//Projection projection = mapView.getProjection(); 
			//Point point = projection.toPixels(message.getPoint(), null);
			mapView.updateViewLayout(messageView,
					new MapView.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT,
							message.getPoint(), MapView.LayoutParams.BOTTOM_CENTER)); 
			
			TextView author = (TextView) messageView.findViewById(R.id.message_bubble_author);
			TextView content = (TextView) messageView.findViewById(R.id.message_bubble_content);
			TextView comments = (TextView) messageView.findViewById(R.id.message_bubble_comments);
			TextView location = (TextView) messageView.findViewById(R.id.message_bubble_location);
			TextView time = (TextView) messageView.findViewById(R.id.message_bubble_time);
			author.setText(message.getAuthor());
			content.setText(message.getSnippet());
			if(message.getComments() == null){
				comments.setText("0");
			}else{
				comments.setText(String.valueOf(message.getComments().size()));
			}
			location.setText(message.getLocationDesc());
			SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
			time.setText(dateFormat.format(message.getTime()));
			//定义动画
			AlphaAnimation animation = new AlphaAnimation(0.3f, 1.0f);
			animation.setDuration(1500);
			messageView.startAnimation(animation);
			messageView.setVisibility(View.VISIBLE);
			
			return true;
		}

		@Override
		public boolean onTap(GeoPoint arg0, MapView arg1) {
			messageView.setVisibility(View.GONE);
			return super.onTap(arg0, arg1);
		}
	}
}